﻿using System.Diagnostics.Contracts;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal struct CondFmtStructure
    {
        private ushort _ccf;
        private bool _fToughRecalc ;
        private int _nid;
        private Ref8U _refBound;
        private SqRefU _sqref;

        public CondFmtStructure(ConditionalFormatting conditionalFormatting, int id)
        {
            _sqref = SqRefU.FromRange(conditionalFormatting.Range);
            _refBound = (Ref8U) conditionalFormatting.Range.Address;
            _fToughRecalc = true;
            _nid = id;
            _ccf = (ushort) conditionalFormatting.Rules.Count;
        }

        public ushort AnId
        {
            get
            {
                var result = (ushort) (_nid << 1);
                if (_fToughRecalc)
                    result |=
                        0x01;
                return result;
            }
        }

        public void Read(BinaryReader reader)
        {
#if DEBUG
            ReadWriteChecker.CheckStruct((ref CondFmtStructure t, BinaryReader r) => t.Read(r),
                                         (ref CondFmtStructure t, BinaryWriter w) => t.Write(w), reader, ref this);
#endif
            _ccf = reader.ReadUInt16();
            ushort anid = reader.ReadUInt16();
            _fToughRecalc = (anid & 0x01) != 0;
            _nid = anid >> 1;
            Contract.Assert(AnId == anid);
            _refBound.Read(reader);
            _sqref = new SqRefU();
            _sqref.Read(reader);
        }

        public void Write(BinaryWriter writer)
        {
            writer.Write(_ccf);
            writer.Write(AnId);
            _refBound.Write(writer);
            _sqref.Write(writer);
        }

        public Range GetRange(Worksheet worksheet)
        {
            return _sqref.ToRange(worksheet);
        }
    }
}